package org.surelink.radius.console;

import org.surelink.radius.cache.GroupCache;
import org.surelink.radius.console.message.Request;
import org.surelink.radius.console.message.RespBase;
import org.surelink.radius.console.message.Response;
import de.tototec.cmdoption.CmdOption;
import de.tototec.cmdoption.CmdlineParser;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class GroupMetaProcess  extends BaseProcess{

    @Autowired
    private GroupCache groupCache;

    class Config{
        @CmdOption(names = {"--help"}, description = "打印帮助",isHelp = true)
        private boolean help;

        @CmdOption(names = {"set"} ,description = "设置用户组属性")
        private boolean set;

        @CmdOption(names = {"get"} ,description = "查询用户组属性")
        private boolean get;

        @CmdOption(names = {"groupmeta"}, description = "设置用户组属性命令",hidden = true)
        boolean setgmeta;

        @CmdOption(names = {"--group", "-g"},args={"groupName"},minCount=1,description = "组名")
        String groupname;

        @CmdOption(names = {"--metas", "-m"}, args = {"metaName", "metaValue"}, minCount = 1,maxCount = -1,
                description = "属性： 属性名称 属性值")
        final Map<String, String> metas = new LinkedHashMap<String, String>();
    }

    public GroupMetaProcess() {
        setOperate("groupmeta");
    }

    @Override
    public Response process(Request req) throws IOException {
        Config config = new Config();
        CmdlineParser cp = new CmdlineParser(config);
        cp.setProgramName(getOperate());
        cp.parse(req.getCommand().split("\\s+"));

        if(config.help){
            StringBuilder sb = new StringBuilder();
            cp.usage(sb);
            return new Response(RespBase.SUCCESS.getCode(),sb.toString());
        }
        if(config.set)  {

            Map<String,String> metas = config.metas;
            for(Map.Entry<String,String> meta:metas.entrySet())
            {
                groupCache.setGroupMeta(config.groupname,meta.getKey(),meta.getValue());
            }
            return RespBase.SUCCESS;
        }
        else if(config.get)
        {
            Map<String,String> metas = groupCache.getGroupMetas(config.groupname);
            if(metas==null)
            {
                return new Response(RespBase.NOT_EXIST_ERR.getCode(),"用户组属性不存在");
            }
            return new Response(metas);
        }

        return RespBase.MSG_FORMAT_ERR;

    }
}
